package com.liuda066.forumssm.controller;

import com.liuda066.forumssm.common.AppResult;
import com.liuda066.forumssm.common.ResultCode;
import com.liuda066.forumssm.config.AppConfig;
import com.liuda066.forumssm.exception.ApplicationException;
import com.liuda066.forumssm.model.User;
import com.liuda066.forumssm.services.IUserService;
import com.liuda066.forumssm.utils.MD5Utils;
import com.liuda066.forumssm.utils.StringUtils;
import com.liuda066.forumssm.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/9/1 22:18
 */
@Api(tags = "用户接口")
@RestController
@Slf4j

@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService iUserService;
    @Value("${photo.base-path}")
    private String BASE_FILE_PATH;
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam(value = "姓名") @RequestParam("username") @NonNull String username,
                              @ApiParam(value = "昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam(value = "密码") @RequestParam("password") @NonNull String password,
                              @ApiParam(value = "确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        if (StringUtils.isEmpty(username)
                || StringUtils.isEmpty(nickname)
                || StringUtils.isEmpty(password)
                ||StringUtils.isEmpty(passwordRepeat)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //处理密码
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        String salt = UUIDUtils.UUID_32();
        String encryptPassword = MD5Utils.md5Salt(password,salt);
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        iUserService.createNormalUser(user);
        return AppResult.success();
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam(value = "用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam(value = "密码") @RequestParam("password") @NonNull String password){
        User user = iUserService.login(username,password);
        HttpSession session  =request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION_KEY,user);

        return AppResult.success();
    }

    @ApiOperation("用户退出")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        if (session != null){
            session.invalidate();
        }
        return AppResult.success();
    }

    @ApiOperation("获取用户详情")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam(value = "用户Id") @RequestParam(value = "id",required = false) Long id){
        User user = null;
        if (id == null){
            HttpSession session = request.getSession();
            user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        } else {
            user = iUserService.selectById(id);
        }
        return AppResult.success(user);
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                @ApiParam("电话号") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark){
        // 非空校验，所有的参数不能同时为空
        if (StringUtils.isEmpty(username) && StringUtils.isEmpty(nickname)
                &&StringUtils.isEmpty(email) && StringUtils.isEmpty(phoneNum)
                &&StringUtils.isEmpty(remark) && gender==null ){
            return AppResult.failed("请输入要修改的内容");
        }
        // 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION_KEY);
        // 构造更新对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        // 调用Service
        iUserService.modifyInfo(updateUser);
        // 获取数据库中最新的User信息
        user = iUserService.selectById(user.getId());
        // 更新session中的User对象
        session.setAttribute(AppConfig.USER_SESSION_KEY,user);
        return AppResult.success(user);
    }
    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //新密码和确认密码是否相同
        if (!newPassword.equals(passwordRepeat)){
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //获取当前用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        //调用
        iUserService.modifyPassword(user.getId(),newPassword,oldPassword);
        //销毁
        if (session != null){
            session.invalidate();
        }
        return AppResult.success();
    }

    //修改头像
    /**
     * 文件上传
     *
     * @param request 请求
     * @param file    文件
     * @return AppResult
     * @throws Exception ApplicationException
     */
    @PostMapping("/uploadPhoto")
    public AppResult jqueryUpload(HttpServletRequest request, MultipartFile file) {
        //没有选择文件
        if (file == null) {
            return AppResult.failed("请选择文件");
        }
        //拿到原始文件的后缀之后生成一个和原始文件后缀名一样的随机文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUIDUtils.UUID_32()+ suffix;
        //文件的全路径
        String fileFullPath = BASE_FILE_PATH + fileName;
        System.out.println(fileFullPath);
        try {
            file.transferTo(new File(fileFullPath));
        } catch (IOException e) {
            throw new ApplicationException("文件上传失败");
        }
        //得到当前登录的用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        //修改数据库中当前用户的头像信息
        user.setAvatarUrl(fileName);
        iUserService.modifyInfo(user);
        //修改session中当前用户的头像信息
        session.setAttribute(AppConfig.USER_SESSION_KEY, user);

        return AppResult.success(fileName);
    }

    /**
     * 文件下载
     *
     * @param fileName 文件名
     * @param response 响应
     */
    @GetMapping("/downloadPhoto")
    public void download(String fileName, HttpServletResponse response) {
        try {
            //获得要显示到浏览器的图片的输入流
            FileInputStream fileInputStream = new FileInputStream(BASE_FILE_PATH + fileName);
            //获得输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //从输入流读数据然后写到输出流
            int len = 0;
            byte[] bytes = new byte[100];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, 100);
                outputStream.flush();
            }
            //关闭资源
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
